import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {Button, Image, View} from '@tarojs/components'
import {
  BASE_URL,
  FACE,
  GET_INTERGRAL,
  GET_PHONE,
  OCR,
  SAVE_REST_TO_USER,
  TARO_ENV,
  UPLODE_FALE
} from "../../constants/api";
import {getHeadTop, GetRequest} from "../../utils/tools";
import Headerbar from "../components/header-bar/header-bar";
import {AtButton, AtForm, AtIcon, AtInput, AtModal, AtModalAction, AtModalContent, AtModalHeader} from "taro-ui";
import {http} from "../../utils/http";
import {platform} from "../../utils/platform-settting.service";
import {user} from "../../utils/user.service";
import {newHttp} from "../../utils/request";
import WxValidate from "../../utils/wx-validate";
import './reclaimer.scss'
import {h5Wx} from "../../utils/h5.service";
import {lxH5Wx} from "../../utils/lx.h5.service";

interface ServerPhone {
  phoneNumber: string
  purePhoneNumber: string
  countryCode: string
  watermark: {
    timestamp: number
    appid: string
  }
}

interface LoginParamType {
  nickName: string
  gender: number
  language: string
  city: string
  province: string
  country: string
  avatarUrl: string
  bindSellerId: number
  itemUUID: string
  path: string
}

// eslint-disable-next-line @typescript-eslint/class-name-casing
export default class reclaimer extends Component {
  state: {
    url: string
    searchBarTop: number
    userForm: {
      name: string
      phone: string
      idcard: string
      company: string
      remark: string
    }
    submitting: boolean
    loginParam: LoginParamType
    modalShow: boolean
    errList: {
      name: boolean
      phone: boolean
      idcard: boolean
      company: boolean
      remark?: boolean
    }
    submiting: boolean
  } = {
    url: '',
    searchBarTop: 0,
    userForm: {
      name: '',
      phone: '',
      idcard: '',
      company: '',
      remark: ''
    },
    submitting: false,
    loginParam: {
      nickName: '',
      gender: 1,
      language: '',
      city: '',
      province: '',
      country: '',
      avatarUrl: '',
      bindSellerId: 0,
      itemUUID: '',
      path: '',
    },
    errList: {
      name: false,
      phone: false,
      idcard: false,
      company: false,
      remark: false,
    },
    submiting: false,
    modalShow: false
  }
  loginmsg = null

  async UNSAFE_componentWillMount() {
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 40) : (headTop.statusBar + headTop.top + 40)
    this.setState({searchBarTop})
  }

  async componentDidShow() {
    const that = this
    const loginParam = this.state.loginParam
    Taro.login().then(async code => {
      user.code = code.code
      const ret = await user.doLogin(loginParam)
      if (!ret) {
        Taro.showToast({
          title: '授权失败,请退出小程序重试',
          icon: 'none'
        })
        return
      }
      that.loginmsg = ret
    })
    const {url} = Taro.getCurrentInstance().router.params;
    this.setState({url})
  }

  uplodeImg(group = 0) {
    const that = this
    const {userForm} = this.state
    userForm['idcard'] = ''
    this.setState({userForm})
    const apiList = [OCR, UPLODE_FALE, FACE]
    const api = BASE_URL + apiList[group]
    if (process.env.TARO_ENV === 'h5') {
      if (process.env.P_ENV === 'lx') {
        lxH5Wx.chooseImage(async (files, length) => {
          lxH5Wx.uploadOcr(files, length, (data) => {
            userForm.idcard = data.idcard
            that.setState({userForm})
          })
        }, 1)
      } else {
        h5Wx.chooseImage(1, ret => {
          Taro.showToast({
            title: group === 0 ? '正在识别...' : '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          h5Wx.wxuploadImage(ret, async res => {
            const dataRet = await newHttp.catchPost(api, {media_id: res}, true)
            Taro.hideToast();
            if (dataRet.status == 400) {
              Taro.showToast({
                title: dataRet.message,
                icon: 'none'
              })
              return
            }
            if (group === 0) {
              if (dataRet && dataRet.idcard) {
                userForm.idcard = dataRet.idcard
              }
            }
            that.setState({userForm})
            Taro.hideLoading()
          })
        })
      }
    } else {
      Taro.chooseImage({
        count: 1,  //最多可以选择的图片总数
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths;
          //启动上传等待中...
          Taro.showToast({
            title: group === 2 ? '正在识别...' : '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          let uploadImgCount = 0;
          for (let i = 0, h = tempFilePaths.length; i < h; i++) {
            Taro.uploadFile({
              url: api,
              filePath: tempFilePaths[i],
              name: group === 2 ? 'face' : 'file',
              formData: {
                'imgIndex': i
              },
              header: http.getHeader(),
              success: function (res) {
                uploadImgCount++;
                const data = JSON.parse(res.data);
                if (res.statusCode == 400) {
                  Taro.showToast({
                    title: data.message,
                    icon: 'none'
                  })
                  return
                }
                if (group === 0) {
                  if (data.data && data.data.idcard) {
                    userForm.idcard = data.data.idcard
                  }
                }
                //如果是最后一张,则隐藏等待中
                if (uploadImgCount == tempFilePaths.length) {
                  that.setState({userForm})
                  Taro.hideToast();
                }
              },
              fail: ()=> {
                Taro.hideToast();
                Taro.showModal({
                  title: '错误提示',
                  content: '上传图片失败',
                  showCancel: false
                })
              }
            })
          }
        }
      })
    }
  }

  jump(url) {
    Taro.navigateTo({
      url
    })
  }

  handleChange(name, value) {
    this.state.userForm[name] = value
  }

  rules = {
    name: {
      required: true,
      minlength: 2
    },
    phone: {
      required: true,
      tel: true
    },
    idcard: {
      required: true
    },
    company: {
      required: true
    },
  }
  message = {
    name: {
      required: "姓名不能为空",
      minlength: "姓名不能小于2个字符"
    },
    phone: {
      required: "手机号不能为空",
      tel: "手机号码不正确"
    },
    idcard: {
      required: "身份证号不能为空",
    },
    company: {
      required: "单位名称不能为空",
    },
  }

  async submit() {
    const {userForm} = this.state
    this.setState({submiting: true}, async () => {
      const validate = new WxValidate(this.rules, this.message)
      if (!validate.checkForm(userForm)) {
        const oldData = this.state.errList
        if (validate && validate.errorList && validate.errorList[0].param) {
          oldData[validate.errorList[0].param] = true
          Taro.showToast({
            title: validate.errorList[0].msg,
            icon: 'none'
          })
        }
        this.setState({errList: oldData, submiting: false})
        return false;
      } else {
        this.saveForm()
      }
    })
  }

  async saveForm() {
    let params = Object.assign({}, this.state.userForm);
    if(process.env.P_ENV === 'kontai') params.version = "v1";
    const ret = await http.HPost(GET_INTERGRAL, params, true)
    if (ret.data) {
      if(ret.data.is_fail && ret.data.is_fail === "fail") {
        this.setState({modalShow: false, submiting: false})
        Taro.showModal({
          title: '提示',
          content: `${ret.data.data}。 ${ret.data.phone}`,
          success: (res) => {
            if (res.confirm) {
            }
          }
        })
      }else {
        Taro.showModal({
          title: '提交成功',
          content: ret.data,
          cancelText: '取消',
          confirmText: '确定',
          confirmColor: '#FAB747',
          success: async function (res) {
            if (res.confirm) {
              Taro.switchTab({url: '/pages/my/index/index'})
            } else {
              Taro.switchTab({url: '/pages/my/index/index'})
            }
          }
        })
      }
    } else {
      this.setState({modalShow: false, submiting: false})
      Taro.showModal({
        title: '提示',
        content: ret.message + '400-9918-499',
        success: (res) => {
          if (res.confirm) {
          }
        }
      })
    }
  }

  async getPhoneNumber(data) {
    const platformInfo = await platform.getSetting()
    this.setState({platformInfo, isLogin: true})
    if (data && data.detail && data.detail.errMsg.indexOf('ok') > -1) {
      this.setState({submitting: true}, async () => {
        const res = await http.post<ServerPhone>(GET_PHONE, {
          encryptedData: data.detail.encryptedData,
          iv: data.detail.iv
        })
        if (res) {
          const {userForm} = this.state
          userForm.phone = res.phoneNumber
          Taro.setStorageSync('wxPhone', true)
          this.setState({submitting: false, userForm})
          user.isLogin = true
        } else {
          Taro.showModal({
            title: '提示',
            content: '需要获取手机号，请打开"使用我的用户信息", 然后再点击登录',
            success: (res) => {
              if (res.confirm) {
                Taro.openSetting()
              } else {
                Taro.navigateBack()
              }
            }
          })
          console.log('getPhoneNumber: fail')
        }
      })
    }
  }

  handleClose() {
    this.saveForm()
    this.setState({modalShow: false, submiting: false})
  }

  handleCancel() {
    this.setState({modalShow: false, submiting: false})
  }

  async handleConfirm() {
    this.setState({modalShow: false, submiting: false})
    await newHttp.catchPost(SAVE_REST_TO_USER, this.state.userForm)
    this.saveForm()
  }

  render() {
    const {submiting, searchBarTop, userForm, modalShow, errList} = this.state
    return (
      <View className='reclaimer-wrapper'>
        <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
          <Headerbar title='信息审核' />
        </View>
        <View className='wrap'>
          <View className='title-box'>
            <View className='title-text'>
              <View>填写以下信息</View>
              <View><Image className='iconImg'
                src='https://resource.ivcheng.com/resources/tianyiyou/images/reclaimer-icon.png'
                mode='widthFix'
              /></View>
              <View>提交审核</View>
              <View><Image className='iconImg'
                src='https://resource.ivcheng.com/resources/tianyiyou/images/reclaimer-icon.png'
                mode='widthFix'
              /></View>
              <View>完成审核</View>
            </View>
            <View className='title-img'>
              <Image className='reclaimer-one'
                src='https://resource.ivcheng.com/resources/tianyiyou/images/reclaimer-1.png' mode='widthFix'
              />
            </View>
          </View>
          <View className='form-box'>
            <AtForm className='person' customStyle='margin-top:20rpx;'>
              <AtInput error={errList.name} className='require' name='name' type='text'
                value={userForm.name} title='姓名' placeholder='真实姓名'
                onChange={this.handleChange.bind(this, 'name')}
              >
              </AtInput>
              <AtInput error={errList.phone} className='require' name='phone' type='number'
                value={userForm.phone} title='手机号码' maxLength={11} placeholder='手机号'
                onChange={this.handleChange.bind(this, 'phone')}
              >
                {TARO_ENV != 'h5' && <AtButton style='height: 40px' openType='getPhoneNumber'
                  onGetPhoneNumber={this.getPhoneNumber.bind(this)} className='get-phone-btn'
                >获取</AtButton>}
              </AtInput>
              <AtInput error={errList.idcard} className='require' name='idcard' type='idcard'
                value={userForm.idcard} maxLength={18} title='身份证号' placeholder='身份证号'
                onChange={this.handleChange.bind(this, 'idcard')}
              >
                <AtIcon onClick={this.uplodeImg.bind(this, 0)} prefixClass='car' value='iconhexiao2' size='18'
                  color='#FCAA09'
                />
              </AtInput>
              <AtInput error={errList.company} className='require' name='address' type='text'
                value={userForm.company} title='单位全称' placeholder='单位全称'
                onChange={this.handleChange.bind(this, 'company')}
              />

              <AtInput error={errList.remark} name='remark' type='text' value={userForm.remark} title='备注'
                placeholder='特殊备注信息'
                onChange={this.handleChange.bind(this, 'remark')}
              />
            </AtForm>
            <View>
              <Image className='reclaimerImg'
                src='https://resource.ivcheng.com/resources/tianyiyou/images/reclaimer-2.png'
                mode='widthFix'
              />
            </View>
            <View onClick={this.jump.bind(this, '/main/tyy/cooperation')}>
              <Image className='reclaimerImg'
                src='https://resource.ivcheng.com/resources/tianyiyou/images/reclaimer-3.png'
                mode='widthFix'
              />
            </View>
          </View>
          <View className='submit-box'>
            <AtButton onClick={this.submit.bind(this)} disabled={submiting} className='submit-btn'
              circle
            >提交审核</AtButton>
          </View>
        </View>
        <AtModal isOpened={modalShow} onClose={this.handleCancel.bind(this)}>
          <AtModalHeader>提示</AtModalHeader>
          <AtModalContent>
            是否为本人操作?
            <AtIcon onClick={this.handleCancel.bind(this)} className='iconicon_tips_wrong' size='30px'
              prefixClass='car' value='iconicon_tips_wrong'
              color='#fff'
            />
          </AtModalContent>
          <AtModalAction>
            <Button onClick={this.handleClose.bind(this)}>否</Button>
            <Button onClick={this.handleConfirm.bind(this)}>是</Button>
          </AtModalAction>
        </AtModal>
      </View>
    );
  }
}
